package com.rocksdata.mc.ui.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ctz.commonframe.constant.DeviceInfo;
import com.ctz.commonframe.ui.BaseFragment;
import com.ctz.commonframe.ui.view.CustomHorizontalScrollView;
import com.ctz.commonframe.ui.view.EmbeddedListView;
import com.ctz.commonframe.ui.widget.AbsAdapter;
import com.ctz.commonframe.ui.widget.AdapterViewHolder;
import com.ctz.commonframe.utils.DateUtil;
import com.ctz.commonframe.utils.DensityUtil;
import com.rocksdata.mc.R;
import com.rocksdata.mc.business.UserInfoManager;
import com.rocksdata.mc.entity.CourseInfo;
import com.rocksdata.mc.entity.UserInfo;
import com.rocksdata.mc.entity.WeekTimetableInfo;
import com.rocksdata.mc.ui.activity.DayTimetableActivity;
import com.rocksdata.mc.ui.activity.TimetableActivity;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by 陈堂正 on 2017/2/13.
 */

@ContentView(R.layout.fragment_week_timetable2)
public class WeekTimetableFragment2 extends BaseFragment {
    private static final int VISIBLE_DAY_COUNT = 14;
    private static final int WIDTH_LEFT_LIST = 30;//dp
    private static final int HEIGHT_TOP_LIST = 45;//dp
    private static final String[] INDEX_MORNING = {"1", "2", "3", "4"};
    private static final String[] INDEX_AFTERNOON = {"5", "6", "7", "8"};
    private static final String[] INDEX_EVENING = {"9", "10"};
    private int formStep; //正方形表格的边长 px
    private int divideWidth;

    //顶部日期标题栏
    @ViewInject(R.id.hsv_top)
    private CustomHorizontalScrollView hsvTop;
    @ViewInject(R.id.layout_top)
    private LinearLayout layoutTop;

    //上午课表
    @ViewInject(R.id.lv_index_morning)
    private EmbeddedListView lvIndexMorning;
    @ViewInject(R.id.hsv_morning)
    private CustomHorizontalScrollView hsvTimetableMorning;
    @ViewInject(R.id.layout_timetable_morning)
    private LinearLayout layoutTimetableMorning;

    //下午课表
    @ViewInject(R.id.lv_index_afternoon)
    private EmbeddedListView lvIndexAfternoon;
    @ViewInject(R.id.hsv_afternoon)
    private CustomHorizontalScrollView hsvTimetableAfternoon;
    @ViewInject(R.id.layout_timetable_afternoon)
    private LinearLayout layoutTimetableAfternoon;

    //晚上课表
    @ViewInject(R.id.lv_index_evening)
    private EmbeddedListView lvIndexEvening;
    @ViewInject(R.id.hsv_evening)
    private CustomHorizontalScrollView hsvTimetableEvening;
    @ViewInject(R.id.layout_timetable_evening)
    private LinearLayout layoutTimetableEvening;

    //所有横向滑动的容器，放在集合用于联动控制
    private List<CustomHorizontalScrollView> linkageViewList = new ArrayList<>();
    //所有课
    private List<List<CourseInfo>> weekCourseList = new ArrayList<>(VISIBLE_DAY_COUNT);
    //所有上午课
    private List<CourseInfo[]> morningCourseList;
    //所有下午课
    private List<CourseInfo[]> afternoonCourseList;
    //所有晚上课
    private List<CourseInfo[]> eveningCourseList;
    //所有适配器，用于刷新
    private List<TimetableInfoListAdapter> adapterList = new ArrayList<>();

    private AdapterView.OnItemClickListener onCourseClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TimetableInfoListAdapter adapter = (TimetableInfoListAdapter) parent.getAdapter();
            CourseInfo info = adapter.getItem(position);
            if(info != null){
                ((TimetableActivity)mContext).showCourseDialog(info, adapter.getDateMillis());
            }
        }
    };

    private CustomHorizontalScrollView.OnScrollChangedListener onScrollChangedListener = new CustomHorizontalScrollView.OnScrollChangedListener() {
        @Override
        public void onScrollChanged(CustomHorizontalScrollView scrollView, int x, int y, int oldx, int oldy) {
            for(CustomHorizontalScrollView v: linkageViewList){
                if(v != scrollView){
                    v.smoothScrollTo(x, y);
                }
            }
        }
    };

    public void setDatas(List<WeekTimetableInfo> infoList){
//        long firstDayMillis = DateUtil.string2Millis(infoList.get(0).getWeekDay(), DateUtil.DATE_FORMAT_YYYY_MM_DD + " " + DateUtil.TIME_FORMAT_HH_MM_SS);
//
//        for(WeekTimetableInfo weekInfo: infoList){
//            weekCourseList.add(weekInfo.getD1());
//            weekCourseList.add(weekInfo.getD2());
//            weekCourseList.add(weekInfo.getD3());
//            weekCourseList.add(weekInfo.getD4());
//            weekCourseList.add(weekInfo.getD5());
//            weekCourseList.add(weekInfo.getD6());
//            weekCourseList.add(weekInfo.getD7());
//        }
//
//        for(int i = 0; i < weekCourseList.size(); i++) {
//            List<CourseInfo> list = weekCourseList.get(i);
//            for (CourseInfo courseInfo : list) {
//                if (courseInfo.getLesson() < 5) {
//                    morningCourseList.get(i)[courseInfo.getLesson() - 1]  = courseInfo;
//                } else if (courseInfo.getLesson() < 9) {
//                    afternoonCourseList.get(i)[courseInfo.getLesson() - 5]  = courseInfo;
//                } else {
//                    eveningCourseList.get(i)[courseInfo.getLesson() - 9]  = courseInfo;
//                }
//            }
//        }
//
//        for(int i = 0; i < adapterList.size(); i++){
//            int day = i / 3;
//            TimetableInfoListAdapter adapter = adapterList.get(i);
//            adapter.setDateMillis(day * DateUtil.MILLIS_PER_DAY + firstDayMillis);
//            adapter.notifyDataSetChanged();
//        }
//
//        for(int i = 0; i < layoutTop.getChildCount(); i++){
//            View v = layoutTop.getChildAt(i);
//            TextView tvDayOfMonth = (TextView) v.findViewById(R.id.tv_day_of_week);
//            TextView tvDate = (TextView) v.findViewById(R.id.tv_date);
//            final long dayMillis = firstDayMillis + i * DateUtil.MILLIS_PER_DAY;
//            if(DateUtil.getDayOfWeekIndex(dayMillis) == DateUtil.getDayOfWeekIndex(System.currentTimeMillis())){
//                v.setBackgroundColor(mContext.getResources().getColor(android.R.color.holo_orange_dark));
//            }
//            tvDayOfMonth.setText(DateUtil.getDayOfWeek(dayMillis));
//            tvDate.setText(DateUtil.millis2String(dayMillis, DateUtil.DATE_FORMAT_MM_DD));
//            final List<CourseInfo> list = weekCourseList.get(i);
//            v.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Intent intent = new Intent(mContext, DayTimetableActivity.class);
//                    intent.putExtra("timetable_data", (Serializable)list);
//                    intent.putExtra("timetable_date", dayMillis);
//                    startActivity(intent);
//                }
//            });
//        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        divideWidth = DensityUtil.dip2px(mContext, 1);
        //边长为(屏幕宽度 - 左侧标题宽度 - 5个分割线宽度) / 5
        formStep = (DeviceInfo.screenWidth - DensityUtil.dip2px(mContext, WIDTH_LEFT_LIST) - 5 * divideWidth) / 5;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        //上侧标题向左空出长度为 左侧标题 + 1个分割线宽度
        hsvTop.setPadding(DensityUtil.dip2px(mContext, WIDTH_LEFT_LIST) + 1, 0, 0, 0);
        for(int i = 0; i < VISIBLE_DAY_COUNT; i++){
            View v = LayoutInflater.from(mContext).inflate(R.layout.item_timetable_date_list, null);
            v.setLayoutParams(new LinearLayout.LayoutParams(formStep + divideWidth, LinearLayout.LayoutParams.WRAP_CONTENT));
            layoutTop.addView(v);
        }

        linkageViewList.add(hsvTop);
        linkageViewList.add(hsvTimetableMorning);
        linkageViewList.add(hsvTimetableAfternoon);
        linkageViewList.add(hsvTimetableEvening);

        for(CustomHorizontalScrollView v: linkageViewList){
            v.setOnScrollChangedListener(onScrollChangedListener);
        }

        LinearLayout.LayoutParams indexListViewParams =
                new LinearLayout.LayoutParams(DensityUtil.dip2px(mContext, WIDTH_LEFT_LIST), ViewGroup.LayoutParams.WRAP_CONTENT);
        lvIndexMorning.setLayoutParams(indexListViewParams);
        lvIndexAfternoon.setLayoutParams(indexListViewParams);
        lvIndexEvening.setLayoutParams(indexListViewParams);
        lvIndexMorning.setAdapter(new IndexListAdapter(mContext, INDEX_MORNING));
        lvIndexAfternoon.setAdapter(new IndexListAdapter(mContext, INDEX_AFTERNOON));
        lvIndexEvening.setAdapter(new IndexListAdapter(mContext, INDEX_EVENING));

        morningCourseList = new ArrayList<>();
        afternoonCourseList = new ArrayList<>();
        eveningCourseList = new ArrayList<>();
//        for(int i = 0; i < VISIBLE_DAY_COUNT; i++){
//            createCourseListView(CourseInfo.DAY_ZONE_MORNING);
//            createCourseListView(CourseInfo.DAY_ZONE_AFTERNOON);
//            createCourseListView(CourseInfo.DAY_ZONE_EVENING);
//        }

        super.onViewCreated(view, savedInstanceState);
    }

    private void createCourseListView(int dayZone){
//        int courseSize = dayZone == CourseInfo.DAY_ZONE_EVENING ? 2 : 4;
//        CourseInfo[] list = new CourseInfo[courseSize];
//        EmbeddedListView listView = new EmbeddedListView(mContext);
//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(formStep, formStep * courseSize + (courseSize - 1) * divideWidth);
//        params.setMarginStart(divideWidth);
//        listView.setLayoutParams(params);
//        listView.setDivider(new ColorDrawable(Color.TRANSPARENT));
//        listView.setDividerHeight(divideWidth);
//        listView.setSelector(new ColorDrawable(Color.TRANSPARENT));
//        listView.setVerticalScrollBarEnabled(false);
//        listView.setHorizontalScrollBarEnabled(false);
//        switch (dayZone){
//            case CourseInfo.DAY_ZONE_MORNING:
//                morningCourseList.add(list);
//                layoutTimetableMorning.addView(listView);
//                break;
//            case CourseInfo.DAY_ZONE_AFTERNOON:
//                afternoonCourseList.add(list);
//                layoutTimetableAfternoon.addView(listView);
//                break;
//            case CourseInfo.DAY_ZONE_EVENING:
//                eveningCourseList.add(list);
//                layoutTimetableEvening.addView(listView);
//                break;
//        }
//        TimetableInfoListAdapter adapter = new TimetableInfoListAdapter(mContext, list);
//        listView.setAdapter(adapter);
//        adapterList.add(adapter);
//        listView.setOnItemClickListener(onCourseClickListener);
    }

    private class IndexListAdapter extends AbsAdapter<String>{

        public IndexListAdapter(Context context, String[] datas) {
            super(context, Arrays.asList(datas), R.layout.item_index_list);
        }

        @Override
        public void convert(AdapterViewHolder holder, String data) {
            TextView tvIndex = holder.getView(R.id.tv_index);
            tvIndex.setText(data);
        }
    }

    private class TimetableInfoListAdapter extends BaseAdapter{
        private long dateMillis;
        private CourseInfo[] dataList;
        private Context context;

        public TimetableInfoListAdapter(Context context, CourseInfo[] dataList) {
            this.context = context;
            this.dataList = dataList;
        }

        public void setDateMillis(long dateMillis){
            this.dateMillis = dateMillis;
        }

        public long getDateMillis(){
            return dateMillis;
        }

        @Override
        public int getCount() {
            return dataList.length;
        }

        @Override
        public CourseInfo getItem(int position) {
            return dataList[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if(convertView == null){
                holder = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.item_timetable_info_list, null);
                holder.layoutParent = (RelativeLayout) convertView.findViewById(R.id.layout_parent);
                holder.tvCourseName = (TextView) convertView.findViewById(R.id.tv_course_name);
                holder.ivStatus = (ImageView) convertView.findViewById(R.id.iv_course_status);
                holder.flagSameCourse = (ImageView) convertView.findViewById(R.id.iv_flag_same_course);

                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }
            final CourseInfo info = getItem(position);
            if(info == null){
                holder.tvCourseName.setText("");
                holder.ivStatus.setVisibility(View.INVISIBLE);
            }else{
                if(info.getChange() == CourseInfo.STATUS_TEST){
                    holder.tvCourseName.setText("考试");
                    holder.tvCourseName.setTextColor(context.getResources().getColor(android.R.color.holo_orange_dark));
                }else {
                    holder.tvCourseName.setText(info.getCourseName());
                    holder.tvCourseName.setTextColor(Color.BLACK);
                }
                switch (info.getChange()) {
                    case CourseInfo.STATUS_CHANGE_TEACHER:
                        holder.ivStatus.setVisibility(View.VISIBLE);
                        holder.ivStatus.setImageResource(R.mipmap.ic_teacher_changed);
                        break;
                    case CourseInfo.STATUS_CHANGE_COURSE:
                        holder.ivStatus.setVisibility(View.VISIBLE);
                        holder.ivStatus.setImageResource(R.mipmap.ic_course_changed);
                        break;
                    default:
                        holder.ivStatus.setVisibility(View.INVISIBLE);
                        break;
                }
                boolean isSameCourse = false;
                int userType = UserInfoManager.getCurrentUserType();
                CourseInfo nextCourse = position < getCount() - 1 ? getItem(position + 1) : null;
                CourseInfo preCourse = position > 0 ? getItem(position - 1) : null;

                if(nextCourse != null){
                    if(userType == UserInfo.USER_TYPE_STUDENT && nextCourse.getCourseCode().equals(info.getCourseCode())){
                        isSameCourse = true;
                    }
                    if(userType == UserInfo.USER_TYPE_TEACHER && nextCourse.getCourseCode().equals(info.getCourseCode()) && nextCourse.getClassCode().equals(info.getClassCode())){
                        isSameCourse = true;
                    }
                }
                if(preCourse != null){
                    if(userType == UserInfo.USER_TYPE_STUDENT && preCourse.getCourseCode().equals(info.getCourseCode())){
                        isSameCourse = true;
                    }
                    if(userType == UserInfo.USER_TYPE_TEACHER && preCourse.getCourseCode().equals(info.getCourseCode()) && preCourse.getClassCode().equals(info.getClassCode())){
                        isSameCourse = true;
                    }
                }

                holder.flagSameCourse.setVisibility(isSameCourse ? View.VISIBLE: View.INVISIBLE);
            }

            return convertView;
        }

        class ViewHolder{
            RelativeLayout layoutParent;
            TextView tvCourseName;
            ImageView ivStatus;
            ImageView flagSameCourse;
        }
    }
}
